import requests, json
import os, threading


headers = {
    'Referer':
    'https://pixivic.com/dailyRank',
    'Sec-Fetch-Dest':
    'image',
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
}

#解析图片json
class Handle(object):
    #新建文件夹，无法创建则pass
    def __init__(self,url):
        self.url = url
        try:
            os.mkdir('download')
        except FileExistsError:
            pass

    #请求页面json 返回data
    def rjson(self):
        req = requests.get(self.url, headers=headers).text
        if req == '{"message":"获取排行成功"}':
            return False
        else:
            data = json.loads(req)['data']
            return data

    #解析data，合成url，并返回一个列表
    def ajson(self):
        #拉取json
        text = self.rjson()
        #一页有多少张图片
        num = len(text)
        #创建列表
        imglist = []
        #循环处理
        for i in range(num):
            dic = {}
            #处理出title和url
            title = text[i]['title']
            url = text[i]['imageUrls'][0]['original'].replace(
                'https://i.pximg.net/', 'https://original.img.cheerfun.dev/')
            #去广告
            if title != 'AkkoCloud 我的世界面板':
                #合成字典
                dic['title'] = title
                dic['url'] = url
            #追加到列表
            imglist.append(dic)
        return imglist

#控制下载页面
class Control(object):
    '''参数说明
    p: 页数,测试时上限为10. 在大于30后页面显示不可大于30
    date: 日期  
    mdoe: 排行榜类型 day  week  month
    '''
    def __init__(self,p,date,mdoe):
        self.url = f'https://api.pixivic.com/ranks?page={p}&date={date}&mode={mdoe}'

    #下载
    def download(self,title,url):
        req = requests.get(url,headers=headers)
        #判断文件类型
        if 'png' in url:
            imgtype = 'png'
        else:
            imgtype = 'jpg'
        #判断文件是否存在
        x = 1
        imgname = f'{title}.{imgtype}'
        while not os.path.exists(imgname):
            title = title + str(x)
            x += 1
        #下载
        with open(f'{title}.{imgtype}') as f:
            f.write(req.content)

    #16线程下载
    def thread(self):
        #拉取列表
        handle = Handle(self.url)
        handle.rjson()
        imglist = handle.ajson()
        #开启多线程下载，线程上线29
        for i in range(16):
            t=threading.Thread(target=run,args=("t- %s"%i,))

        



ic = Handle('https://api.pixivic.com/ranks?page=1&date=2020-03-09&mode=day')
ic.rjson()
ic.ajson()
ic.download()
